package org.csu.cms.controller;

import org.csu.cms.domain.Account;
import org.csu.cms.result.Code;
import org.csu.cms.result.Result;
import org.csu.cms.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class AccountControllor {
    @Autowired
    private SupplierService supplierService;


    /**
     * 查询用户信息
     */
    @GetMapping("/userinfo")
    public Result AccountInfo() {
        List<Account> accountList = supplierService.getAllAccount();
        String msg = "";
        if (accountList != null) {
            Result result = new Result(Code.GET_OK, accountList, msg);
            return result;
        } else {
            msg = "查询失败";
            Result result = new Result(Code.GET_ERR, msg);
            return result;
        }
    }


    /**
     * 更新用户信息
     */
    @PutMapping(value = "/userinfo/update/{id}")
    public Result updateAccountInfo(@PathVariable Long id, @RequestBody Account updateAccount) {
        Account account = supplierService.updateAccount(id, updateAccount);
        String msg = "";
        if (account != null) {
            return new Result(Code.UPDATE_OK, msg);
        } else {
            msg = "更新失败，更新用户不存在";
            return new Result(Code.UPDATE_ERR, msg);
        }
    }

    /**
     * 更改用户密码
     */
    @PutMapping(value = "/userinfo/password/{id}")
    public Result updateAccountPassword(@PathVariable Long id, @RequestParam("password") String password, @RequestParam("new_password") String new_password) {
        String msg = supplierService.updatePassword(supplierService.getAccountById(id), password, new_password);
        if (msg.equals("ok")) {
            return new Result(Code.UPDATE_OK, msg);
        } else {
            return new Result(Code.UPDATE_ERR, msg);
        }
    }

    /**
     * 重置用户密码
     */
    @PutMapping(value = "/userinfo/reset/{id}")
    public Result resetAccountPassword(@PathVariable Long id) {
        //重置密码为123456
        String msg = supplierService.resetPassword(supplierService.getAccountById(id));
        if (msg.equals("ok")) {
            return new Result(Code.UPDATE_OK, msg);
        } else {
            return new Result(Code.UPDATE_ERR, msg);
        }
    }


    /**
     * 删除用户
     */
    @DeleteMapping(value = "/userinfo/delete/{id}")
    public Result deleteAccount(@PathVariable Long id) {
        Account account = supplierService.getAccountById(id);
        String msg = "";
        if (account != null) {
            supplierService.deleteAccount(id);
            return new Result(Code.DELETE_OK, msg);
        } else {
            msg = "删除异常";
            return new Result(Code.DELETE_ERR, msg);
        }
    }

}
